package org.example.link_list;

public class MyLinkedList {
    int size;
    ListNode head; //虚拟头节点
    public MyLinkedList(){
        this.size = 0;
        this.head = new ListNode(0);
        this.head.next = null;
    }

    public int get(int index){
        if (index<0 || index > this.size-1){
            return -1;
        }
        ListNode currentNode = head;
        for (int i = 0;i<=index;i++){
            currentNode = currentNode.next;
        }
        return currentNode.val;
    }
    public void addAtHead(int val){
        ListNode listNode = new ListNode(val);
        listNode.next = head.next;
        head.next = listNode;
        this.size++;
    }

    public void addAtTail(int val) {
        ListNode node = new ListNode(val);
        ListNode p = head;
        while (p.next!=null){
            p = p.next;
        }
        p.next = node;
        node.next = null;
        this.size++;
    }

    public void addAtIndex(int index, int val) {
        int num = this.size;
        if (index==num){
            this.addAtTail(val);
        }
        if (index<num){
            ListNode node = new ListNode(val);
            ListNode beforeNode = head;
            for (int i = 0;i<index;i++){
                beforeNode = beforeNode.next;
            }
            node.next = beforeNode.next;
            beforeNode.next = node;
            this.size++;
        }
    }
    public void deleteAtIndex(int index) {
        if (0<= index && index<this.size){
            ListNode beforeNode = head;
            for (int i = 0;i<index;i++){
                beforeNode = beforeNode.next;
            }
            ListNode currentNode = beforeNode.next;
            beforeNode.next = currentNode.next;
            currentNode.next = null;
            this.size--;
        }
    }

    public void show(){
        ListNode p = head;
        for(int i = 0;i<this.size;i++){
            p = p.next;
            System.out.print(p.val+" ");
        }
    }
}
